<template>
  <div class="profile-name">
    <van-nav-bar
        class="app-nav-bar"
        title="更改昵称"
        right-text="完成"
        left-arrow
        @click-left="$emit('close')"
        @click-right="onClickRight"
    />
    <van-field v-model="profileName"
               maxlength="10"
               :rules="[{ required: true, message: '请填写用户名' }]"/>
    <van-cell>好名字可以让你的朋友更容易记住你</van-cell>
  </div>
</template>

<script>
import {updateUserProfile} from "@/api/user";

export default {
  name: "profileName",
  props:{
    name:{
      type:String,
      required:true
    }
  },
  data(){
    return{
      profileName:this.name
    }
  },
  methods:{
    async onClickRight(){
      this.$toast.loading({
        message:'保存中',
        forbidClick:true
      })
      try {
        await updateUserProfile({
          name:this.profileName
        })
        this.$toast.success('保存成功')
        this.$emit('update-name',this.profileName)
        this.$emit('close')
      }catch (err){
        if (err&&err.response&&err.response.status===409){
          this.$toast.fail('昵称已存在')
        }
      }
    }
  }
}
</script>

<style scoped lang="less">
/deep/.van-nav-bar__content{
  background-color: #3a8ee6;
}
</style>